<template>
  <a-menu>
    <a-menu-item key="1" @click="changeIcon">
      <template #icon>
        <SwapOutlined />
      </template>
      更换图标
      <SelectIcon v-model:visible="selecticonShow" @selectIcon="selectIcon" />
    </a-menu-item>
    <a-menu-item key="2" @click="deleteFile">
      <template #icon>
        <DeleteOutlined />
      </template>
      删除
    </a-menu-item>
    <a-menu-item key="3" @click="rename">
      <template #icon>
        <EditOutlined />
      </template>
      重命名
    </a-menu-item>
  </a-menu>
</template>

<script lang="ts">
import { defineComponent, ref, createVNode } from 'vue'
import { Modal } from 'ant-design-vue'
import { SyncOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { services } from '@/services'
import { FilesModel } from '@/services/service'
import SelectIcon from '@/components/SelectIcon.vue'

export default defineComponent({
  name: 'contextmenu',
  components: { SyncOutlined, SelectIcon },
  props: {
    id: {
      type: Number,
      default: 0
    },
    fileMap: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['success', 'fail'],
  setup(props, ctx) {
    const selecticonShow = ref(false)
    let selectFile = {} as FilesModel

    /** 修改图标 点击显示图标选择 */
    function changeIcon() {
      selecticonShow.value = true
      selectFile = props.fileMap[props.id]
    }
    async function selectIcon(key: string) {
      selectFile.icon = key

      let res = await services.updataFile(selectFile)
      if (res.code) {
        ctx.emit('success')
      } else {
        ctx.emit('fail')
      }
    }

    /** 删除文件 / 文件夹 */
    async function deleteFile() {
      Modal.confirm({
        title: '确认删除',
        icon: createVNode(ExclamationCircleOutlined),
        content: '没有回收站功能, 文件删除不可找回!',
        async onOk() {
          let file = props.fileMap[props.id]
          let res = await services.deleteFile(file.id, file.article_id)
          if (res.code) {
            ctx.emit('success')
          } else {
            ctx.emit('fail')
          }
        },
        onCancel() {}
      })
    }

    /** 重命名 */
    async function rename() {
      let name = prompt('请输入文件名')
      if (!name) return

      let file = props.fileMap[props.id]
      let res = await services.updataFile({ ...file, name })

      if (res.code) {
        ctx.emit('success')
      } else {
        ctx.emit('fail')
      }
    }

    return {
      selecticonShow,
      changeIcon,
      selectIcon,
      deleteFile,
      rename
    }
  }
})
</script>

<style lang="less" scoped></style>
